from django.shortcuts import render
from rest_framework_jwt.views import ObtainJSONWebToken
from .serializers import CustomeSerializer, RegisterModelSerializer
from rest_framework.views import APIView
import  re
from rest_framework.response import Response
from rest_framework import status
from .utils import get_user_obj
from rest_framework.generics import CreateAPIView
from . import models
# Create your views here.



class CustomLoginView(ObtainJSONWebToken):
    serializer_class = CustomeSerializer


class CheckPhoneNumber(APIView):
    def get(self,request):
        phone_number = request.GET.get('phone')
        if not re.match('^1[3-9]\d{9}$', phone_number):
            return Response({'error_msg':'手机号格式有误，请重新输入!'}, status = status.HTTP_400_BAD_REQUEST)
        ret = get_user_obj(phone_number)
        if ret:
            return Response({'error_msg':'手机号已被注册，请换手机号!'}, status= status.HTTP_400_BAD_REQUEST)
        return Response({'msg':'ok'}, status=status.HTTP_200_OK)


class RegisterView(CreateAPIView):
    queryset = models.User.objects.all()
    serializer_class = RegisterModelSerializer

import re, random

from django_redis import get_redis_connection
from lyapi.settings import contains

class GetSMSCodeView(APIView):

    # create verified code
    def get(self, request, phone):
        sms_code = '%06d'%random.randint(0,999999)
        conn = get_redis_connection("sms_code")
        ret = conn.get("mobile_interval_%s"%phone)
        if ret:
            return Response({'msg':"60秒内已经发送过了，别瞎搞"}, status=status.HTTP_400_BAD_REQUEST)
    # save verified code

        conn.setex("mobile_%s"%phone, sms_code, contains.SMS_CODE_EXPIRE_TIME)
        conn.setex("mobile_interval_%s"%phone, sms_code, contains.SMS_CODE_INTERVAL_TIME)

        # 发送验证码
        # send verified code
        from celery.result import AsyncResult
        from mycelery.sms.tasks import sms_codes
        sms_codes.delay(phone, sms_code)

        return Response({'msg': "ok"})













































